package com.wuwei.elearning.setting.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwei.elearning.question.domain.TestAnswers;
import com.wuwei.elearning.question.domain.TestResult;
import com.wuwei.elearning.question.mapper.TestAnswersMapper;
import com.wuwei.elearning.question.mapper.TestResultMapper;
import com.wuwei.elearning.setting.domain.User;
import com.wuwei.elearning.setting.mapper.UserMapper;
import com.wuwei.elearning.setting.service.UserService;
import com.wuwei.elearning.utils.result.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Resource
    private UserMapper userMapper;

    @Resource
    private TestResultMapper testResultMapper;

    @Resource
    private TestAnswersMapper testAnswersMapper;


    @Override
    public Result<String> setPassword(User user, Long account, String newPassword) {
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(account!=null,User::getAccount,account);
        user.setAccount(account);
        user.setPassword(newPassword);
        int update = userMapper.update(user, updateWrapper);
        if (update!=1) {
            return Result.fail("密码修改失败！数据库修改失败");
        }
        return Result.ok("密码修改成功！");
    }

    /**
     * 删除用户信息的方法，除了删除user表，还要删除test_answers表和test_result表
     * @param id
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        User user = userMapper.selectById(id);
        userMapper.deleteById(id);

        LambdaQueryWrapper<TestResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TestResult::getAccount,user.getAccount());
        testResultMapper.delete(queryWrapper);

        LambdaQueryWrapper<TestAnswers> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(TestAnswers::getUserId,user.getAccount());
        testAnswersMapper.delete(queryWrapper1);
    }

}
